package com.tepth.maintenancesystem.untils;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.api.MaintainHttp;
import com.tepth.maintenancesystem.untils.bleNfc.DeviceManager;
import com.tepth.maintenancesystem.untils.bleNfc.DeviceManagerCallback;
import com.tepth.maintenancesystem.untils.bleNfc.Scanner;
import com.tepth.maintenancesystem.untils.bleNfc.ScannerCallback;
import com.tepth.maintenancesystem.untils.bleNfc.card.Mifare;
import com.tepth.maintenancesystem.untils.bleNfc.card.Ultralight;

import java.util.ArrayList;
import java.util.Vector;

import butterknife.ButterKnife;

import static com.tepth.maintenancesystem.untils.bleNfc.card.Mifare.MIFARE_KEY_TYPE_A;
import static java.lang.Thread.State.NEW;
import static java.lang.Thread.State.RUNNABLE;

/**
 * Created by LHQ on 2017/1/4.
 */

public class NFCManger {


    private static DeviceManager deviceManager;
    private static Scanner mScanner;
    private static BluetoothDevice mNearestBle = null;
    private static int lastRssi = -100;

    private static Context _context;
    private static NFCInterface nfcInterface;
    private static SearchCard thread;
//    private static ArrayList<String> address_list=new ArrayList<>();
//    private static boolean listOut=false;

    public static void createDeviceManager(Context context, NFCInterface inter) {
        _context = context;
        if (BluetoothManager.turnOnBluetooth()) {
            //初始设备操作类
            mScanner = new Scanner(context, scannerCallback);
            deviceManager = new DeviceManager(context);
            deviceManager.setCallBack(deviceManagerCallback);

            startGetDevice(inter, context);
        } else {
            ToastUtils.showToast(context, "请打开蓝牙在操作");
        }
    }

    public static int isConnection() {
        if (deviceManager == null) {
            return 0;
        }
        if (!deviceManager.isConnection())
            return 1;
        else
            return 2;
    }

    public static void startGetCard(NFCInterface nfc) {
        nfcInterface = nfc;
        if (deviceManager.isConnection())
            if (nfcInterface != null) {
                nfcInterface.successConnectionDevice();
            }
        if (thread != null)
            LL = false;
        thread = new SearchCard();
        thread.start();
    }

    static boolean LL = false;

    private static class SearchCard extends Thread {
        @Override
        public void run() {
            Action<Integer> action = new Action<Integer>() {
                @Override
                public void invoke(Integer i) {
                    if (i == 0) {
                        isScand = 0;

                    } else if (i == 1) {
                        isScand = 2;
                        LL = false;
                    }
                }
            };
            try {
                Thread.sleep(1000);
                int index = 0;
                isScand = 0;
                LL = true;
                while (true) {
                    if (!stopGetDevicedList) {
                        break;
                    } else if (LL) {
                        if (isScand == 0) {
                            isScand = 1;
                            scanCard(action);
                        } else {
                            try {
                                Thread.sleep(500);
                                index++;
                                if (index > 30 * 4) {
                                    if (nfcInterface != null)
                                        nfcInterface.stopSearchCard();
                                    break;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    } else break;
                }
                super.run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                LL = false;
                isScand = 0;
            }
        }
    }

    public static void stopSearchCard() {
        LL = false;
    }

    static int isScand = 0;

    public static class DeviceManagerOnReceiveRfnSearchCardListener implements DeviceManager.onReceiveRfnSearchCardListener {

        private Action<Integer> _action;

        public DeviceManagerOnReceiveRfnSearchCardListener(Action<Integer> action) {
            _action = action;
        }

        @Override
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            deviceManager.mOnReceiveRfnSearchCardListener = null;
            if (!blnIsSus) {
                //未找到卡片
                _action.invoke(0);
                return;
            }
            if (cardType == DeviceManager.CARD_TYPE_ULTRALIGHT) {   //寻到ULTRALIGHT卡
                final Ultralight card = (Ultralight) deviceManager.getCard();
                Ultralight.onReceiveReadListener readModel = new Ultralight.onReceiveReadListener() {
                    byte[] data = new byte[48];
                    int index = 0;

                    @Override
                    public void onReceiveRead(boolean isSuc, byte[] returnBytes) {
                        if (isSuc) {
                            try {
                                int j = index * 16;
                                for (int i = 0; i < returnBytes.length; i++) {
                                    data[j++] = returnBytes[i];
                                }
                                index++;
                                if (index >= 3) {
                                    int len = 0;
                                    for (int i = data.length - 1; i >= 0; i--) {
                                        if (data[i] != 0) {
                                            len = i;
                                            break;
                                        }
                                    }
                                    byte[] d = new byte[len + 1];
                                    for (int i = 0; i < d.length; i++) {
                                        d[i] = data[i];
                                    }
                                    //打卡成功
                                    if (nfcInterface != null) {
                                        nfcInterface.successCard(d);
                                        _action.invoke(1);
                                        return;
                                    }
                                    card.close(null);
                                } else {
                                    Thread.sleep(300);
                                    card.read((byte) (index * 4 + 16), this);
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {

                        }
                        _action.invoke(0);
                    }
                };
                card.read((byte) 16, readModel);
            } else if (cardType == DeviceManager.CARD_TYPE_MIFARE) {
                final Mifare card = (Mifare) deviceManager.getCard();
                final Mifare.onReceiveReadListener readModel = new Mifare.onReceiveReadListener() {
                    byte[] data = new byte[48];
                    int index = 0;

                    @Override
                    public void onReceiveRead(boolean isSuc, byte[] returnBytes) {
                        if (isSuc) {
                            try {
                                int j = index * 16;
                                for (int i = 0; i < returnBytes.length; i++) {
                                    data[j++] = returnBytes[i];
                                }
                                index++;
                                if (index >= 3) {
                                    int len = 0;
                                    for (int i = data.length - 1; i >= 0; i--) {
                                        if (data[i] != 0) {
                                            len = i;
                                            break;
                                        }
                                    }
                                    byte[] d = new byte[len + 1];
                                    for (int i = 0; i < d.length; i++) {
                                        d[i] = data[i];
                                    }
                                    //打卡成功
                                    if (nfcInterface != null) {
                                        nfcInterface.successCard(d);
                                        _action.invoke(1);
                                        return;
                                    }
                                    card.close(null);
                                } else {
                                    Thread.sleep(300);
                                    card.read((byte) (4 + index), this);
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {

                        }
                        _action.invoke(0);
                    }
                };
                card.authenticate((byte) 4, MIFARE_KEY_TYPE_A, new byte[]{(byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255}, new Mifare.onReceiveAuthenticateListener() {
                    @Override
                    public void onReceiveAuthenticate(boolean isSuc) {
                        if (isSuc)
                            card.read((byte) 4, readModel);
                        else
                            _action.invoke(0);
                    }
                });
            } else {
                _action.invoke(0);
            }
        }
    }

    public static void scanCard(Action<Integer> action) {
        if (!deviceManager.isConnection()) {
            action.invoke(0);
            return;
        }
        if (nfcInterface != null) {
            nfcInterface.searchCard();
        }
        try {
            deviceManager.requestRfmSearchCard((byte) 0x01, new DeviceManagerOnReceiveRfnSearchCardListener(action));
        } catch (Exception e) {
            action.invoke(0);
        }
    }

    public static ScannerCallback scannerCallback = new ScannerCallback() {
        @Override
        public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
            super.onReceiveScanDevice(device, rssi, scanRecord);
            System.out.println("Activity搜到设备：" + device.getName() + "信号强度：" + rssi);
            //搜索蓝牙设备并记录信号强度最强的设备
            if ((device.getName() != null) && (device.getName().contains("UNISMES") || device.getName().contains("BLE_NFC"))) {
                if (mNearestBle != null) {
//                    if (rssi > lastRssi) {
                    mNearestBle = device;
//                    }
                } else {
                    mNearestBle = device;
                    lastRssi = rssi;
                }
                if (!nfcmac_list.contains(device.getAddress()))
                    nfcmac_list.add(device.getAddress());
            }
        }

        @Override
        public void onScanDeviceStopped() {
            super.onScanDeviceStopped();
        }
    };

    //设备操作类回调
    public static DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectBtDevice(boolean blnIsConnectSuc) {
            super.onReceiveConnectBtDevice(blnIsConnectSuc);
            if (blnIsConnectSuc) {
                System.out.println("Activity设备连接成功");
                //连接上后延时500ms后再开始发指令
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startGetCard(nfcInterface);
                if (nfcInterface != null) {
                    nfcInterface.successConnectionDevice();
                }
            }
        }

        @Override
        public void onReceiveDisConnectDevice(boolean blnIsDisConnectDevice) {
            super.onReceiveDisConnectDevice(blnIsDisConnectDevice);
            System.out.println("Activity设备断开链接");

            //连接上后延时500ms后再开始发指令
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            startGetDevice(nfcInterface, _context);
        }

        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            super.onReceiveConnectionStatus(blnIsConnection);
            System.out.println("Activity设备链接状态回调");
        }

        @Override
        public void onReceiveInitCiphy(boolean blnIsInitSuc) {
            super.onReceiveInitCiphy(blnIsInitSuc);
        }

        @Override
        public void onReceiveDeviceAuth(byte[] authData) {
            super.onReceiveDeviceAuth(authData);
        }

        @Override
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus) {
                return;
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < bytCardSn.length; i++) {
                stringBuffer.append(String.format("%02x", bytCardSn[i]));
            }

            StringBuffer stringBuffer1 = new StringBuffer();
            for (int i = 0; i < bytCarATS.length; i++) {
                stringBuffer1.append(String.format("%02x", bytCarATS[i]));
            }
            System.out.println("Activity接收到激活卡片回调：UID->" + stringBuffer + " ATS->" + stringBuffer1);
        }

        @Override
        public void onReceiveRfmSentApduCmd(byte[] bytApduRtnData) {
            super.onReceiveRfmSentApduCmd(bytApduRtnData);

            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < bytApduRtnData.length; i++) {
                stringBuffer.append(String.format("%02x", bytApduRtnData[i]));
            }
            System.out.println("Activity接收到APDU回调：" + stringBuffer);
        }

        @Override
        public void onReceiveRfmClose(boolean blnIsCloseSuc) {
            super.onReceiveRfmClose(blnIsCloseSuc);
        }
    };

    public static boolean connectionBluetooth() {
        try {
            if (deviceManager.isConnection()) {
//                deviceManager.requestDisConnectDevice();
                return true;
            }
            if (!mScanner.isScanning()) {
                mScanner.startScan(0);
                mNearestBle = null;
                lastRssi = -100;
                int searchCnt = 0;
                while ((mNearestBle == null) && (searchCnt < 5000) && (mScanner.isScanning())) {
                    searchCnt++;
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (mNearestBle != null) {
                    // /storage/emulated/0/tepth/NFCMAC.txt
                    // /storage/sdcard0/tepth/NFCMAC.txt
//                     address = FileUtils.getNFC_MAC_File(FileUtils.getInnerSDCardPath() + "/tepth/NFCMAC.txt").trim();
//                    if (address.equals("")) {
                    String address = Untils.getNFCMAC(_context);
                        if (address.equals("")) {
                            return false;
                        } else {
                            if (address.equals(mNearestBle.getAddress())) {
                                if (!stopGetDevicedList) {
                                    return true;
                                } else {
                                    mScanner.stopScan();
                                    if (nfcInterface != null) {
                                        nfcInterface.connectionDevice();
                                    }
                                    deviceManager.requestConnectBleDevice(mNearestBle.getAddress());
                                    return true;
                                }
                            } else {
                                return false;
                            }
                        }
//                    } else {
//                        if (address.equals(mNearestBle.getAddress())) {
//                            if (!stopGetDevicedList) {
//                                return true;
//                            } else {
//                                mScanner.stopScan();
//                                if (nfcInterface != null) {
//                                    nfcInterface.connectionDevice();
//                                }
//                                deviceManager.requestConnectBleDevice(mNearestBle.getAddress());
//                                return true;
//                            }
//                        } else {
//                            return false;
//                        }
//                    }
                } else {
                    //未搜索到设备
                    return false;
                }
            } else {
                if (mNearestBle != null) {
                    // /storage/emulated/0/tepth/NFCMAC.txt
                    // /storage/sdcard0/tepth/NFCMAC.txt
//                     address = FileUtils.getNFC_MAC_File(FileUtils.getInnerSDCardPath() + "/tepth/NFCMAC.txt").trim();
//                    if (address.equals("")) {
                        String address = Untils.getNFCMAC(_context);
                        if (address.equals("")) {
                            return false;
                        } else {
                            if (address.equals(mNearestBle.getAddress())) {
                                if (!stopGetDevicedList) {
                                    return true;
                                } else {
                                    mScanner.stopScan();
                                    if (nfcInterface != null) {
                                        nfcInterface.connectionDevice();
                                    }
                                    deviceManager.requestConnectBleDevice(mNearestBle.getAddress());
                                    return true;
                                }
                            } else {
                                return false;
                            }
                        }
//                    } else {
//                        if (address.equals(mNearestBle.getAddress())) {
//                            if (!stopGetDevicedList) {
//                                return true;
//                            } else {
//                                mScanner.stopScan();
//                                if (nfcInterface != null) {
//                                    nfcInterface.connectionDevice();
//                                }
//                                deviceManager.requestConnectBleDevice(mNearestBle.getAddress());
//                                return true;
//                            }
//                        } else {
//                            return false;
//                        }
//                    }
                } else {
                    //未搜索到设备
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    public static void startGetDevice(NFCInterface nfc, Context context) {
        _context = context;
        nfcInterface = nfc;
        if (nfcInterface != null) {
            nfcInterface.searchDevice();
        }
        new Thread() {
            @Override
            public void run() {

                while (true) {
                    if (!stopGetDevicedList) {
                        break;
                    } else if (connectionBluetooth()) {
                        break;
                    } else {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                super.run();
            }
        }.start();
    }

    public static void startScanAndGetDevicedList(NFCInterface nfc, Context context) {
        _context = context;
        if (mScanner == null || deviceManager == null)
            if (BluetoothManager.turnOnBluetooth()) {
                //初始设备操作类
                mScanner = new Scanner(context, scannerCallback);
                deviceManager = new DeviceManager(context);
                deviceManager.setCallBack(deviceManagerCallback);

            } else {
                ToastUtils.showToast(context, "请打开蓝牙在操作");
            }
//        if (!mScanner.isScanning())
//            mScanner.startScan(0);
        if (!mScanner.isScanning()) {
            mScanner.startScan(0);
        } else {
            mScanner.stopScan();
            mScanner.startScan(0);
        }
        getDevicedList(nfc);
    }

    public static boolean stopGetDevicedList = true;

    static int tempCount = 0;

    static Vector<String> nfcmac_list = new Vector<>();

    public static void setStopGetDevicedList(boolean stop) {
        stopGetDevicedList = stop;
    }

    public static void getDevicedList(NFCInterface nfc) {
        nfcmac_list.clear();
        stopGetDevicedList = false;
        nfcInterface = nfc;
        new Thread() {
            @Override
            public void run() {

                while (true) {
                    if (stopGetDevicedList) {
                        break;
                    } else {
                        tempCount++;
                        if (tempCount % 5 == 0)
                            nfcmac_list.clear();
                        else
                            nfcInterface.updateDeviceList(nfcmac_list);
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                super.run();
            }
        }.start();
    }

//    private static boolean tempInterrupt = false;

    public static void interruptDevice() {
        if (deviceManager == null)
            return;
        if (deviceManager.isConnection()) {
            deviceManager.requestDisConnectDevice();
        }
    }
}
